#Region "Using directives"

Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports C4F.DevKit.Telephony
Imports System.Threading
Imports System.IO
Imports System.Diagnostics
#End Region

Namespace TapiSampleApplication
	Public Partial Class frmTelephony
		Inherits Form
		#Region "Globals"

		Private tapiManager_Renamed As TapiManager
		Private fileRecordCount As Integer = 1
		Private autoAnsweringOptionSelected As Boolean = False
		Private listenVoiceMailsOptionSelected As Boolean = False
		Private voiceMailPlaybackStarted As Boolean = False
		Private userPassword As String = String.Empty
		Public Delegate Sub ChangeStateDelegate(ByVal stateObject As Object)
		Public Delegate Sub ChangeTabState()
		Private callEventLog As TapiCallEventLog = Nothing
		Private settings As Settings = New Settings(Environment.CurrentDirectory & "\")

		#End Region

		#Region "Properties"

		Public Property TapiManager() As TapiManager
			Get
				Return tapiManager_Renamed
			End Get
			Set(ByVal value As TapiManager)
				tapiManager_Renamed = value
			End Set
		End Property

		#End Region

		#Region "Constructors"

		Public Sub New()
			InitializeComponent()
			tapiManager_Renamed = tapiManager1
			AddHandler tapiManager_Renamed.OnIncomingCall, AddressOf tapiManager_OnIncomingCall
			AddHandler tapiManager_Renamed.OnCallConnected, AddressOf tapiManager_OnCallConnected
			AddHandler tapiManager_Renamed.OnCallDisconnected, AddressOf tapiManager_OnCallDisconnected
			AddHandler tapiManager_Renamed.OnOutgoingCall, AddressOf tapiManager_OnOutgoingCall
			AddHandler tapiManager_Renamed.OnCallHold, AddressOf tapiManager_OnCallHold
			AddHandler tapiManager_Renamed.OnDigitReceived, AddressOf tapiManager_OnDigitReceived
			AddHandler tapiManager_Renamed.OnEndOfFilePlayback, AddressOf tapiManager_OnEndOfFilePlayback

			dialPanel1.TapiManager = tapiManager_Renamed
			dtmfPanel1.TapiManager = tapiManager_Renamed
			playbackAndRecordingPanel1.TapiManager = tapiManager_Renamed
		End Sub

		#End Region

		#Region "Tapi Event Handlers"

		Private Sub tapiManager_OnIncomingCall(ByVal [call] As CallInfo)
			' Log Entry For Call.
			LogEntry([call])

			' Check auto answering of incoming call.
			If chkAutoAnswering.Checked = True Then
				Try
					tapiManager_Renamed.AnswerCall()
				Catch ex As Exception
					MessageBox.Show(ex.Message)
				End Try
			' Display Incoming call form to handle incoming call if auto answering is not enabled.
			Else
				Try
					If DialogResult.Yes = MessageBox.Show("Answer call", "Incoming call", MessageBoxButtons.YesNo) Then
						tapiManager_Renamed.AnswerCall([call])
					End If
				Catch exception As Exception
					MessageBox.Show(exception.Message, "Telephony Application", MessageBoxButtons.OK, MessageBoxIcon.Error)
				End Try
			End If
		End Sub

		Private Sub tapiManager_OnCallConnected(ByVal [call] As CallInfo)
			' Log Entry For Call.
			LogEntry([call])

			' Check auto answering of incoming call.
			If chkAutoAnswering.Checked = True Then
				Try
					tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\Welcome.wav")
					' Welcome message time.
					Thread.Sleep(12000)
					tapiManager_Renamed.StopPlayingFile()
					tapiManager_Renamed.StartDigitDetection()
				Catch exception As Exception
					MessageBox.Show(exception.Message, "Telephony Application", MessageBoxButtons.OK, MessageBoxIcon.Error)
				End Try
			Else
				Dim del As ChangeStateDelegate = New ChangeStateDelegate(AddressOf EnableDialOptionsButtons)
				Dim del1 As ChangeStateDelegate = New ChangeStateDelegate(AddressOf EnableResumeButton)
				Dim del2 As ChangeStateDelegate = New ChangeStateDelegate(AddressOf EnableHoldButton)
				Dim del3 As ChangeTabState = New ChangeTabState(AddressOf EnablingTabs)
				If tbAnsweringMachine.InvokeRequired Then
					tbAnsweringMachine.Invoke(del, False)
					tbAnsweringMachine.Invoke(del1, False)
					tbAnsweringMachine.Invoke(del2, True)
					tbAnsweringMachine.Invoke(del3)
				End If
			End If
		End Sub

		Private Sub tapiManager_OnCallDisconnected(ByVal [call] As CallInfo)
			' Log Entry For Call.
			LogEntry([call])

			autoAnsweringOptionSelected = False
			listenVoiceMailsOptionSelected = False
			voiceMailPlaybackStarted = False
			Dim del1 As ChangeStateDelegate = New ChangeStateDelegate(AddressOf EnableDialOptionsButtons)
			Dim del2 As ChangeStateDelegate = New ChangeStateDelegate(AddressOf EnableHoldButton)
			Dim del3 As ChangeStateDelegate = New ChangeStateDelegate(AddressOf EnableDtmf)
			Dim del4 As ChangeStateDelegate = New ChangeStateDelegate(AddressOf EnablePlayback)
			If Dial.InvokeRequired Then
				Dial.Invoke(del1, True)
				Dial.Invoke(del2, False)
				Dial.Invoke(del3, False)
				Dial.Invoke(del4, False)
			End If
		End Sub

		Private Sub tapiManager_OnOutgoingCall(ByVal [call] As CallInfo)
			' Log Entry For Call.
			LogEntry([call])
		End Sub

		Private Sub tapiManager_OnCallHold(ByVal [call] As CallInfo)
			' Log Entry For Call.
			LogEntry([call])

			Dim del1 As ChangeStateDelegate = New ChangeStateDelegate(AddressOf EnableResumeButton)
			Dim del2 As ChangeStateDelegate = New ChangeStateDelegate(AddressOf EnableHoldButton)
			If Dial.InvokeRequired Then
				Dial.Invoke(del1, True)
				Dial.Invoke(del2, False)
			End If
		End Sub

		Private Sub tapiManager_OnDigitReceived(ByVal [call] As CallInfo, ByVal digit As Char)
			' Log Entry For Call.
			LogEntry([call], "Digit Received : " & digit.ToString())

			Try
'				#Region "Auto-answering enabled"

				If chkAutoAnswering.Checked = True Then
'					#Region "Password Verification and Listen Voice Mails"

					If listenVoiceMailsOptionSelected = True AndAlso userPassword.Length < 4 Then
						' Collect password.
						userPassword &= digit.ToString()
						If userPassword.Length = 4 Then
							listenVoiceMailsOptionSelected = False
							' Perform password validation.
							' 4 digit password(Sample passowrd: 1234).
							tapiManager_Renamed.StopDigitDetection()
							If userPassword.Equals("1234") Then
								If (Not Directory.Exists(Environment.CurrentDirectory & "\VoiceMails")) Then
									Directory.CreateDirectory(Environment.CurrentDirectory & "\VoiceMails")
								End If
								Dim voiceMails As String() = Directory.GetFiles("VoiceMails", "CallRecord*.wav")
								If voiceMails.Length = 0 Then
									tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\NoVoiceMails.wav")
									' Message time.
									Thread.Sleep(6000)
									tapiManager_Renamed.DisconnectCall()
									autoAnsweringOptionSelected = False
									Return
								Else
									Dim voiceMailsPaths As List(Of String) = New List(Of String)(voiceMails)
									voiceMailsPaths.Add(Environment.CurrentDirectory & "\..\..\Resources\ThankYou.wav")
									tapiManager_Renamed.PlayFiles(voiceMailsPaths)
									voiceMailPlaybackStarted = True
									autoAnsweringOptionSelected = False
									tapiManager_Renamed.StartDigitDetection()
									Return
								End If
							Else
								tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\InvalidPassword.wav")
								' Message time.
								Thread.Sleep(3000)
								tapiManager_Renamed.DisconnectCall()
								autoAnsweringOptionSelected = False
								Return
							End If

						Else
							Return
						End If
					End If

'					#End Region

'					#Region "Save Voice Message"

					If digit = "1"c AndAlso autoAnsweringOptionSelected = False Then
						autoAnsweringOptionSelected = True
						tapiManager_Renamed.StopDigitDetection()

						tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\LeaveMessage.wav")
						' Message time.
						Thread.Sleep(3500)
						tapiManager_Renamed.StopPlayingFile()

						tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\Beep.wav")
						' Message time.
						Thread.Sleep(1000)
						tapiManager_Renamed.StopPlayingFile()

						If (Not Directory.Exists(Environment.CurrentDirectory & "\VoiceMails")) Then
							Directory.CreateDirectory(Environment.CurrentDirectory & "\VoiceMails")
						End If
						Dim voiceMails As String() = Directory.GetFiles("VoiceMails", "CallRecord*.wav")
						fileRecordCount = voiceMails.Length + 1
						' Start recording.
						tapiManager_Renamed.RecordCall(Environment.CurrentDirectory & "\VoiceMails\CallRecord" & fileRecordCount.ToString() & ".wav")

						' Recording time.
						Thread.Sleep(15000)
						' Stop Recording.
						tapiManager_Renamed.StopCallRecording()
						fileRecordCount += 1

						tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\Beep.wav")
						' Message time.
						Thread.Sleep(1000)
						tapiManager_Renamed.StopPlayingFile()

						tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\ThankYou.wav")
						' Message time.
						Thread.Sleep(2000)
						tapiManager_Renamed.DisconnectCall()
						autoAnsweringOptionSelected = False
						Return

'					#End Region

'					#Region "Password Input"

					ElseIf digit = "2"c AndAlso autoAnsweringOptionSelected = False Then
						listenVoiceMailsOptionSelected = True
						userPassword = String.Empty
						autoAnsweringOptionSelected = True

						tapiManager_Renamed.StartDigitDetection()
						tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\Password.wav")
						' Message time.
						Thread.Sleep(3000)
						tapiManager_Renamed.StopPlayingFile()
						Return

'					#End Region

'					#Region "Delete Voice Mails"

					ElseIf digit = "3"c AndAlso autoAnsweringOptionSelected = False Then
						autoAnsweringOptionSelected = True
						tapiManager_Renamed.StopDigitDetection()
						Dim voiceMailDirectory As String = Environment.CurrentDirectory & "\VoiceMails"
						If Directory.Exists(voiceMailDirectory) Then
							Dim voiceMails As String() = Directory.GetFiles(Environment.CurrentDirectory & "\VoiceMails")
							For Each voiceMail As String In voiceMails
								File.Delete(voiceMail)
							Next voiceMail
							tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\DeleteVoiceMails.wav")
							Thread.Sleep(5000)
						End If
						tapiManager_Renamed.DisconnectCall()
						autoAnsweringOptionSelected = False

'					#End Region

'					#Region "Exit System"

					ElseIf digit = "0"c AndAlso autoAnsweringOptionSelected = False Then
						autoAnsweringOptionSelected = True
						tapiManager_Renamed.StopDigitDetection()
						tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\ThankYou.wav")
						' Message time.
						Thread.Sleep(3000)
						tapiManager_Renamed.DisconnectCall()
						autoAnsweringOptionSelected = False

'					#End Region

'					#Region "Invalid Option"

					Else
						autoAnsweringOptionSelected = True
						tapiManager_Renamed.StopDigitDetection()
						tapiManager_Renamed.PlayFile(Environment.CurrentDirectory & "\..\..\Resources\WrongChoice.wav")
						' Message time.
						Thread.Sleep(5000)
						tapiManager_Renamed.DisconnectCall()
						autoAnsweringOptionSelected = False
					End If

'					#End Region

					Return

'				#End Region

'				#Region "DTMF operation"

				Else
					Dim del1 As ChangeStateDelegate = New ChangeStateDelegate(AddressOf DigitDetectionTextBoxUpdate)
					If DTMF.InvokeRequired Then
						DTMF.Invoke(del1, digit)
					End If
				End If

'				#End Region
			Catch exception As Exception
				MessageBox.Show(exception.Message, "Telephony Application", MessageBoxButtons.OK, MessageBoxIcon.Error)
			End Try
		End Sub

		Private Sub tapiManager_OnEndOfFilePlayback(ByVal [call] As CallInfo)
			' Log Entry For Call.
			LogEntry([call])

			If voiceMailPlaybackStarted = True AndAlso [call].CallState = CallState.Connected Then
				tapiManager_Renamed.DisconnectCall()
			End If


		End Sub

		Private Sub LogEntry(ByVal [call] As CallInfo, ByVal category As String)
			Try
				If chkBoxCallLog.Checked Then
					Trace.Write([call], category)
				End If
			Catch exception As Exception
				MessageBox.Show(exception.Message)
			End Try
		End Sub

		Private Sub LogEntry(ByVal [call] As CallInfo)
			Try
				If chkBoxCallLog.Checked Then
					Trace.Write([call])
				End If
			Catch exception As Exception
				MessageBox.Show(exception.Message)
			End Try
		End Sub

		#End Region

		#Region "Helper Methods"

		Private Sub EnableDialOptionsButtons(ByVal stateObject As Object)
			dialPanel1.DialOptionsButtonsEnabled = CBool(stateObject)
		End Sub

		Private Sub EnableHoldButton(ByVal stateObject As Object)
			dialPanel1.HoldButtonEnabled = CBool(stateObject)
		End Sub

		Private Sub EnableResumeButton(ByVal stateObject As Object)
			dialPanel1.ResumeButtonEnabled = CBool(stateObject)
		End Sub

		Private Sub EnableDtmf(ByVal stateObject As Object)
			dtmfPanel1.DtmfEnabled = CBool(stateObject)
		End Sub

		Private Sub EnablePlayback(ByVal stateObject As Object)
			playbackAndRecordingPanel1.PlaybackEnabled = CBool(stateObject)
		End Sub

		Private Sub EnablePlayStopButtons(ByVal state As Boolean)
			playbackAndRecordingPanel1.PlayStopButtonsEnabled = CBool(state)
		End Sub

		Private Sub EnablePlayBackControls(ByVal state As Boolean)
			playbackAndRecordingPanel1.PlayBackControlsEnabled = CBool(state)
		End Sub

		Private Sub EnableCallRecordingControls(ByVal state As Boolean)
			playbackAndRecordingPanel1.CallRecordingControlsEnabled = CBool(state)
		End Sub

		Private Sub EnablingTabs()
			If tapiManager_Renamed.CurrentCall Is Nothing Then
				dtmfPanel1.DtmfEnabled = False
				playbackAndRecordingPanel1.PlaybackEnabled = False
			Else
				dtmfPanel1.DtmfEnabled = True
				playbackAndRecordingPanel1.PlaybackEnabled = True
			End If
		End Sub

		Private Sub DigitDetectionTextBoxUpdate(ByVal digitObject As Object)
			dtmfPanel1.DigitDetectionTextBoxUpdate(digitObject)
		End Sub

		Private Sub ChangeStateOfClearButton()
			dtmfPanel1.ChangeStateOfClearButton()
		End Sub

		#End Region

		#Region "Event Handlers"

		Private Sub btnClose_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClose.Click
			Me.Close()
		End Sub

		Private Sub tbAnsweringMachine_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbAnsweringMachine.SelectedIndexChanged
			EnablingTabs()
		End Sub

		Private Sub frmTelephony_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs) Handles MyBase.FormClosed
			Try
				tapiManager_Renamed.TapiShutdown()
			Catch exception As Exception
				MessageBox.Show(exception.Message, "Telephony Application", MessageBoxButtons.OK, MessageBoxIcon.Error)
			End Try
		End Sub

		Private Sub chkAutoAnswering_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles chkAutoAnswering.CheckedChanged
			If chkAutoAnswering.Checked = True Then
				' Disable the whole tab contol. 
				tbAnsweringMachine.Enabled = False
			Else
				' Enable the whole tab contol. 
				tbAnsweringMachine.Enabled = True
			End If
		End Sub

		Private Sub chkBoxCallLog_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles chkBoxCallLog.CheckedChanged
			If chkBoxCallLog.Checked = True Then
				' Telephony log listener added. 
				AddTraceListener()
			End If
			If chkBoxCallLog.Checked = False Then
				Trace.Listeners.Remove(callEventLog)
			End If
		End Sub

		Friend Sub AddTraceListener()
			callEventLog = New TapiCallEventLog(settings.GetLogFileName())
			Trace.Listeners.Add(callEventLog)
		End Sub

		Private Sub btnSettings_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSettings.Click
			settings.ShowDialog()
			Trace.Listeners.Remove(callEventLog)
			AddTraceListener()
		End Sub

		#End Region
	End Class
End Namespace
